package com.unis.iptv.common.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Security;
import java.util.Calendar;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @date Aug 2, 2012
 * @author 杨飞宇
 */
public class AuthenticationBase {
	private static Log iptvCourse = LogFactory.getLog("iptvCourse");
	static String epgUrl = "";
	
	public static void main(String[] args) {
		auth();
	}
	
	static void auth() {
		String AuthServer = "http://10.255.0.29:8080/iptvepg/platform/index.jsp";
		String StbId = "841001990070114000034C09B4C43E61";
		String MacAddr = "4C:09:B4:C4:3E:61";
		String IpAddr = "10.249.95.251";
		String UserId = "085130375753@itv";
		String Password = "123456";
		
		try {
			URL authUrl;
			HttpURLConnection conn;
			String lineStr;
			String resporseStr;
			String authInfoStr;
			String Request;
			int Begin, End;
			authUrl = new URL(AuthServer + "?UserID=" + UserId
					+ "&Action=Login");
			conn = (HttpURLConnection) authUrl.openConnection();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				
				resporseStr = "";
				while ((lineStr = in.readLine()) != null) {
					resporseStr += lineStr;
				}
				conn.disconnect();
			} else {
				conn.disconnect();
				System.out.println("URL: " + authUrl.toString() + " Code: "
						+ conn.getResponseCode());
				return;
			}
			System.out.println(resporseStr);
			
			Begin = resporseStr.indexOf("Authentication.CTCGetAuthInfo");
			if (Begin < 0 || (Begin = resporseStr.indexOf("'", Begin)) < 0
					|| (End = resporseStr.indexOf("'", Begin + 1)) < 0) {
				System.out.println("Authentication.CTCGetAuthInfo not found.");
				return;
			}
			authInfoStr = resporseStr.substring(Begin + 1, End);
			System.out.println("AuthInfo: " + authInfoStr);
			Request = "UserID=" + UserId;
			Request += "&Authenticator="
					+ Authenticator(authInfoStr, StbId, MacAddr, IpAddr,
							UserId, Password);
			
			Request += "&AccessMethod=lan";
			Request += "&AccessUserName=" + UserId + "@itv";
			Request = Request.replace("@", "%40");
			System.out.println("Request" + Request);
			
			authUrl = new URL(
					"http://10.255.128.8:8080/iptvepg/platform/auth.jsp");
			// authUrl = new URL(AuthServer.substring(0,
			// AuthServer.lastIndexOf('/'))
			// + "/uploadAuthInfo");
			conn = (HttpURLConnection) authUrl.openConnection();
			conn.setRequestMethod("POST");
			
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setAllowUserInteraction(false);
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", "" + Request.length());
			DataOutputStream OutStream = new DataOutputStream(
					conn.getOutputStream());
			OutStream.writeBytes(Request);
			OutStream.close();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				resporseStr = "";
				while ((lineStr = in.readLine()) != null) {
					resporseStr += lineStr;
				}
				conn.disconnect();
			} else {
				conn.disconnect();
				System.out.println("URL: " + authUrl.toString() + " Code: "
						+ conn.getResponseCode());
				return;
			}
			String UserToken = CTCSetConfig(resporseStr, "UserToken");
			String EPGDomain = CTCSetConfig(resporseStr, "EPGDomain");
			System.out.println("UserToken: " + UserToken);
			authUrl = new URL(EPGDomain + "?UserToken=" + UserToken
					+ "&UserID=" + UserId + "&UserIP=" + IpAddr);
			conn = (HttpURLConnection) authUrl.openConnection();
			
			System.out.println("<<<<<<<<<<<<<<<<<<<<" + authUrl);
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				resporseStr = "";
				while ((lineStr = in.readLine()) != null) {
					resporseStr += lineStr;
				}
				conn.disconnect();
			} else {
				conn.disconnect();
				System.out.println("URL: " + authUrl.toString() + " Code: "
						+ conn.getResponseCode());
				return;
			}
			// System.out.println("@@@@@@@@@@@@@@@@@" + resporseStr);
			// Begin = resporseStr.indexOf("top.document.location");
			// if (Begin < 0 || (Begin = resporseStr.indexOf("'", Begin)) < 0
			// || (End = resporseStr.indexOf("'", Begin + 1)) < 0) {
			// System.out.println("top.document.location not found.");
			// return;
			// }
			// urlStr = resporseStr.substring(Begin + 1, End);
			// System.out.println("EPG URL: " + urlStr);
			
			// ?
			// ?
			// ??
			//
			authUrl = new URL(
					"http://10.255.128.8:8080/iptvepg/frame1008/frame_portal.jsp");
			conn = (HttpURLConnection) authUrl.openConnection();
			
			System.out.println("<<<<<<<<<<<<<<<<<<<<" + authUrl);
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				resporseStr = "";
				while ((lineStr = in.readLine()) != null) {
					resporseStr += lineStr;
				}
				conn.disconnect();
			} else {
				conn.disconnect();
				System.out.println("URL: " + authUrl.toString() + " Code: "
						+ conn.getResponseCode());
				return;
			}
			System.out.println(resporseStr);
			
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	static String CTCSetConfig(String Response, String Name) {
		int Begin, End;
		
		// Authentication.CTCSetConfig('UserToken',
		// '6Dom1uNlQ0ObeJrQrYxdiMH133001710')
		String Key = "Authentication.CTCSetConfig('" + Name + "', '";
		iptvCourse.info("");
		iptvCourse.info(">>>>>>>>>>>>>>>>>>>>>>>key:" + Key);
		iptvCourse.info(">>>>>>>>>>>>>>>>>>>>>>>Response:" + Response);
		iptvCourse.info("");
		Begin = Response.indexOf(Key);
		if (Begin > 0) {
			Begin += Key.length();
			End = Response.indexOf("'", Begin);
			if (End > 0)
				return Response.substring(Begin, End);
		}
		return "";
	}
	
	static public String Authenticator(String AuthInfo, String StbId,
			String MacAddr, String IpAddr, String UserId, String Password) {
		String AuthStr = "";
		String Result = "";
		Random Rand = new Random(Calendar.getInstance().getTimeInMillis());
		AuthStr += String.format("%08d", Rand.nextInt(100000000)) + "$";
		AuthStr += AuthInfo + "$";
		AuthStr += UserId + "$";
		AuthStr += StbId + "$";
		AuthStr += IpAddr + "$";
		AuthStr += MacAddr + "$";
		AuthStr += "990070|$CTC";
		try {
			byte Auth[] = AuthStr.getBytes("ASCII");
			int Len = Auth.length;
			int Mod = Len % 8;
			
			if (Mod != 0)
				Len += 8 - Mod;
			byte AuthBytes[] = new byte[Len];
			
			for (int i = 0; i < Len; i++) {
				if (i >= Auth.length)
					AuthBytes[i] = (byte) (8 - Mod);
				else
					AuthBytes[i] = Auth[i];
			}
			
			String Algorithm = "DESede";
			byte KeyBytes[] = new byte[24];
			byte PassBytes[] = Password.getBytes();
			
			for (int i = 0; i < 24; i++) {
				if (i < PassBytes.length)
					KeyBytes[i] = PassBytes[i];
				else
					KeyBytes[i] = 0x30;
			}
			Security.addProvider(new com.sun.crypto.provider.SunJCE());
			SecretKey DesKey = new SecretKeySpec(KeyBytes, Algorithm);
			Cipher C = Cipher.getInstance(Algorithm);
			C.init(Cipher.ENCRYPT_MODE, DesKey);
			byte Encrypt[] = C.doFinal(AuthBytes);
			for (int i = 0; i < Len; i++) {
				Result += String.format("%02X",
						Encrypt[i] < 0 ? (256 + Encrypt[i]) : Encrypt[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result;
	}
}
